package com.interview01;

import java.util.Arrays;

/**
 * Copyright (C), 2018-2020
 * FileName: Demo2
 * Author:   kongfanyu
 * Date:     2020/12/4 14:46
 */
public class Demo2 {
    public static void main(String[] args) {
        int[] arr = {1,2,3,5,8,11,34};
        int i = binarySearch(arr, 8);
        System.out.println("下标:"+i);
    }

    public static int binarySearch(int arr[], int num){
        int mid = 0; //中间值
        int start = 0;//起始位置
        int end = arr.length -1;//结束位置

        while(start <= end){
            //mid = (end - start) / 2 + start;
            mid = (end + start) / 2 ;
            if ( num < arr[mid] ){
                end = mid  - 1;
            }else if(num > arr[mid]){
                start = mid + 1;
            }else{
                return mid;
            }
        }

        return -1;
    }



    private static void test1() {
        int[] arr = {2,5,1,3,8,11,34};
        //Arrays.sort(arr);
        System.out.println("排序之前:\n"+ Arrays.toString(arr));
        int m  =0;
        for (int i = 0 ;i<arr.length -1; i++){
            System.out.println("比较第 " +  i + "趟");
            for (int j=0; j<arr.length - i - 1; j++){
                m ++;
                if (arr[j] >  arr[j + 1]){
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;

                }
            }
        }
        System.out.println("比较次数："+ m);
        System.out.println("排序之后:\n"+Arrays.toString(arr));
    }
}
